package org.example.server.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.common.exception.AccountNotFoundException;
import org.example.entity.User;
import org.example.server.mapper.OrgInfoMapper;
import org.example.server.mapper.UserMapper;
import org.example.server.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrgInfoMapper orgInfoMapper;


    @Override
    public String getCode(String account) {

        if (account.matches("^1[3456789]\\d{9}$")) {
            Random random = new Random();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 6; i++) {
                int digit = random.nextInt(10); // 生成0到9之间的随机数
                sb.append(digit);
            }

            return sb.toString();
        } else {


            throw new AccountNotFoundException("手机号格式错误");
        }
    }

    @Override
    public void login(String account, String code, String storedCode) {


        if (account != null || code != null) {

            //手机号正则校验
            if (code.equals(storedCode) && account.matches("^1[3456789]\\d{9}$")) {


            } else {
                throw new AccountNotFoundException("手机号或验证码不正确，请重新输入");
            }

        } else {
            log.error("手机号和验证码不能为空");
            throw new AccountNotFoundException("手机号和验证码不能为空");
        }


    }

    @Override
    public User selectById(String currentId) {
        return userMapper.selectById(currentId);
    }

    @Override
    public User selectByMobile(String mobile, String hospitalNo) {
        User user = userMapper.selectByMobile(mobile, hospitalNo);

        if (user == null) {
            User user1 = new User();
            user1.setUserId("1");
            user1.setUserNick("admin");
            user1.setAccount(mobile);
            user1.setStatus(1);
            user1.setCreateTime(new java.util.Date());
            user1.setUpdateTime(new java.util.Date());
            user1.setHospitalNo(hospitalNo);
            userMapper.insert(user1);
            user1.setUserId(String.valueOf(user1.getId()));
            userMapper.updateUserId(user1);

            return user1;
        } else {

            return user;
        }

    }
}
